
//
//  CPJLoginViewController.swift
//  Sina
//
//  Created by yang on 2017/8/6.
//  Copyright © 2017年 成品家（北京）网路科技有限公司. All rights reserved.
//

import UIKit

import SVProgressHUD

class CPJLoginViewController: UIViewController {

    private lazy var webView = UIWebView()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        title = "登录新浪微博"
        view = webView
        webView.delegate = self
        
        //禁止滚动
        webView.scrollView.isScrollEnabled = false
        
        view.backgroundColor = UIColor.white
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(size: CGSize(width: 50, height: 30), titleStr: "关闭", fontSize: 16, target: self, selector:#selector(closeAction), isBack: false)
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(size: CGSize(width: 100, height: 30), titleStr: "自动填充", fontSize: 14, target: self, selector: #selector(autoFill), isBack: false)
        
        let urlString = "\(OAuthUrlString)?client_id=\(SinaAppKey)&redirect_uri=\(SinaAppRedirect_uri)"
        
        //确定URL
        guard let url = URL(string: urlString) else{
            return
        }
        //建立请求
        let request = URLRequest(url: url)
        //加载请求
        webView.loadRequest(request)
        
        // Do any additional setup after loading the view.
    }

    @objc fileprivate func closeAction()
    {
        SVProgressHUD.dismiss()
        dismiss(animated: true, completion: nil)
    }
    
    @objc private func autoFill()
    {
        let js = "document.getElementById('userId').value = '15210351381';" + "document.getElementById('passwd').value = '2890HorseY'"
        
        //执行js
        webView.stringByEvaluatingJavaScript(from: js)
    }
}


extension CPJLoginViewController: UIWebViewDelegate
{
    
    /// 代理方法 原生和js的交互
    ///
    /// - Parameters:
    ///   - webView: webView
    ///   - request: 请求
    ///   - navigationType: 导航栏类型
    /// - Returns: 返回值
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool
    {
        //print(request.url?.absoluteString)
        
        if request.url?.absoluteString.hasPrefix(SinaAppRedirect_uri) == false
        {
            return true
        }
        if request.url?.query?.hasPrefix("code=") == false {
            print("取消授权")
            closeAction()
            return false
        }
        //print(request.url?.query)
        
        let code = request.url?.query?.substring(from: "code=".endIndex) ?? ""
        
        print("授权码：code =  \(code)")
        SVProgressHUD.dismiss()
        CPJNetworkManager.shared.loadAccessToken(code: code) { (success) in
            if success
            {
                //SVProgressHUD.showInfo(withStatus: "网路请求成功")
                
                //发送通知
                NotificationCenter.default.post(name: NSNotification.Name(rawValue: UserLoginSuccessNotification), object: nil)
                self.closeAction()
            }
            else
            {
                SVProgressHUD.showInfo(withStatus: "网路请求失败")
            }
        }
        return false
    }
    
    func webViewDidStartLoad(_ webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
}
